<script setup name="Modeling">
import Tree from '@/views/schedule/components/tree.vue'
import {
  GetTreeAPI,
  GetListAPI,
  AddDataAPI,
  DelDataAPI,
  EditDataAPI,
  GetDetailsAPI,
  GetCutShopModelingAPI,
  GetWarehouseAPI,
  GetXianbianAPI
} from '@/api/system/shopAdministration/modeling'
import { Check, Delete, Edit, Message, Search, Star } from '@element-plus/icons-vue'
const { proxy } = getCurrentInstance()
const { quality_production_level } = proxy.useDict('quality_production_level')

const ruleFormRef = ref(null)

// 新增弹窗
const addIsShow = ref(false)

// 标题
const title = ref('新增')

// 保存加载状态
const Btnloading = ref(false)

// 表格加载状态
const loading = ref(false)

// 表格数据
const TableData = ref([])

// 列表总数量
const total = ref(0)

// 是否禁用删除
const DelDisabled = ref(false)

// 是否禁用 单选
const ExamineDisabled = ref(false)

// 树结构
const treeData = ref([])

// 选中的树结构
const treeRow = ref({})

// 是否禁用表单输入
const disabled = ref(false)

//
const Ids = ref([])
const rows = ref([])

// 查询条件
const SelectList = ref([
  // { type: '日期范围' },
  { label: '区域编码', model: 'modelingCode', type: '输入框', placeholder: '请输入区域编码' },
  { label: '区域名称', model: 'modelingName', type: '输入框', placeholder: '请输入区域名称' }
])

// 新增字段modeling
const ruleForm = reactive({
  modelingTypeDict: '',
  superiorCode: '', // 上级编码
  modelingType: '', // 区域类型  1 工厂 2车间 3线别
  modelingCode: '', // 区域编码
  modelingName: '', // 区域名称
  modelingWidth: '', // 定幅宽
  modelingMinTrimming: '', // 最小切边
  modelingShopRank: '', // 车间生产阶别
  modelingShopNext: '', // 车间下级车间
  modelingBindingStorage: '', // 车间绑定仓库
  modelingStorageType: '' // 车间绑定仓库类型
})

// 表单校验
const rules = reactive({
  superiorCode: [
    { required: true, message: '请填写上级编码', trigger: 'bulr' },
    { validator: proxy.noChinese, trigger: 'blur' }
  ],
  modelingType: [{ required: true, message: '请填写区域类型', trigger: 'bulr' }],
  modelingCode: [
    { required: true, message: '请填写区域编码', trigger: 'blur' },
    { validator: proxy.noChinese, trigger: 'blur' }
  ],
  modelingName: [{ required: true, message: '请填写区域名称', trigger: 'bulr' }],

  modelingMinTrimming: [{ required: true, message: '请填写最小切边', trigger: 'bulr' }],
  modelingWidth: [{ required: true, message: '请填写线别定幅宽', trigger: 'bulr' }],
  // modelingMaxTrimming: [{ required: true, message: '请填写最大切边', trigger: 'blur' }],
  modelingShopRank: [{ required: true, message: '请选择生产阶别', trigger: 'change' }]
})

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  modelingId: ''
})

/**
 * 弹窗
 */
// 新增弹窗
const add = () => {
  getCutShopModeling()
  title.value = '新增'
  isifType()
  getXianbie()
  addIsShow.value = true
}

// 修改弹窗
const edit = async (id, a) => {
  getCutShopModeling()
  getXianbie()
  proxy.$modal.loading('请稍候...')
  try {
    title.value = '修改'
    const res = await GetDetailsAPI(id)
    for (let Key in res.data) {
      ruleForm[Key] = res.data[Key]
    }
    ruleForm.modelingShopRankType = res.data.modelingShopRank
    ruleForm.modelingShopRank = String(ruleForm.modelingShopRank)
    // disabled.value = true
    addIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 查看弹窗
const dxamine = async id => {
  proxy.$modal.loading('请稍候...')
  try {
    title.value = '查看'
    const res = await GetDetailsAPI(id)
    for (let Key in res.data) {
      ruleForm[Key] = res.data[Key]
    }
    ruleForm.modelingShopRank = Number(ruleForm.modelingBindingStorage)

    ruleForm.modelingShopRank = String(ruleForm.modelingShopRank)
    disabled.value = true
    addIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 新增提交
const addSub = async () => {
  try {
    const valid = await ruleFormRef.value.validate()
    if (!valid) return proxy.formMsg()
    Btnloading.value = true
    await AddDataAPI(ruleForm)
    getTree()
    close()
    proxy.successMsg('新增成功')
  } catch {
  } finally {
    Btnloading.value = false
  }
}

// 修改提交
const editSub = async () => {
  try {
    const valid = await ruleFormRef.value.validate()
    if (!valid) return proxy.formMsg()
    Btnloading.value = true
    await EditDataAPI(ruleForm)
    getTree()
    close()
    proxy.successMsg('修改成功')
  } catch {
  } finally {
    Btnloading.value = false
  }
}

// 删除
const del = async val => {
  // console.log(val, 'valvalvalvalvalvalvalvalval')
  const MesBox = await proxy.DelMessageBox()
  if (!MesBox) return
  await DelDataAPI(val ? val : Ids.value.join(','))
  getTree()
  proxy.successMsg('删除成功')
}

// 判断类别 赋值 区域类别为线别时必填
const isifType = async () => {
  if (treeRow.value?.id) {
    const { data: res } = await GetDetailsAPI(treeRow.value.id)
    ruleForm.modelingShopRankType = res.modelingShopRank
    ruleForm.modelingShopRank = res.modelingShopRank
  }

  ruleForm.parentId = treeRow.value.id || null
  if (!treeRow.value?.typeName) {
    ruleForm.modelingTypeDict = '工厂'

    ruleForm.modelingType = 0
    // delete rules.modelingMaxTrimming
  } else if (treeRow.value.typeName == '工厂') {
    ruleForm.modelingTypeDict = '车间'
    ruleForm.modelingType = 1
  } else {
    ruleForm.modelingTypeDict = '线别'
    ruleForm.modelingType = 2
    // rules.modelingWidth = [{ required: true, message: '请填写定幅宽', trigger: 'bulr' }]
  }
  if (treeRow.value?.typeName) ruleForm.superiorCode = treeRow.value.code
}

// 判断生产阶别为水刺且区域为车间时
const modelingShopRankChange = val => {
  ruleForm.modelingId = val.id
}

// 弹窗关闭时
const close = () => {
  addIsShow.value = false
  disabled.value = false
  treeRow.value = {}
  Btnloading.value = false
  for (let Key in ruleForm) {
    ruleForm[Key] = ''
  }
}

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = selection => {
  rows.value = selection
  Ids.value = selection.map(item => item.modelingId)
  DelDisabled.value = !selection.length
  selection.length <= 0 || selection.length > 1 ? (ExamineDisabled.value = true) : (ExamineDisabled.value = false)
}
handleSelectionChange([])

// 选择 树结构
const handleNodeClick = val => {
  if (!val.children) {
    query.parentId = null
    query.modelingId = val.id
  } else {
    query.parentId = val.id
    query.modelingId = null
  }
  treeRow.value = val
  getList()
}

// 查询
const selectSubmit = val => {
  for (let Key in val) {
    query[Key] = val[Key]
  }
  getTree()
}

const init = arr => {
  arr.forEach(item => {
    if (item?.children && item.children.length > 0) {
      item.name = `${item.name} (${item.children.length})`
      init(item.children)
    }
  })
}

// 获取树结构
const getTree = async () => {
  query.parentId = ''
  query.modelingId = ''
  try {
    const res = await GetTreeAPI()
    treeData.value = res.theDrop
    init(treeData.value)
    getList()
  } catch {
  } finally {
  }
}

// 获取列表
const getList = async () => {
  try {
    const res = await GetListAPI(query)
    TableData.value = res.rows
    loading.value = false
    total.value = res.total
  } catch {
  } finally {
    loading.value = false
  }
}

// 车间绑定仓库类型改变时
const modelingStorageTypeChange = val => {
  // 1  仓库 2线边仓

  val == 1 ? getWarehouse() : getXianbie()

  ruleForm.modelingBindingStorage = ''
}

// 分切车间数据
const cutShopModeling = ref([])

const getCutShopModeling = async () => {
  const { data: res } = await GetCutShopModelingAPI()
  cutShopModeling.value = res
}

getTree()

const warehouseSel = ref([])
const getWarehouse = async () => {
  const { data: res } = await GetWarehouseAPI()
  warehouseSel.value = res.map(item => ({
    label: item.warehouseName,
    value: item.id
  }))
}

const getXianbie = async () => {
  const { rows: res } = await GetXianbianAPI({
    pageNum: 1,
    pageSize: 99999
  })
  console.log(res)
  warehouseSel.value = res.map(item => ({
    label: item.warehouseName,
    value: item.id
  }))
}
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <SelectForm :SelectForm="SelectList" @selectSubmit="selectSubmit" />
    <div class="flex mt10">
      <!-- 树结构 -->
      <el-card class="treeClass" style="height: 32.6rem; overflow: auto">
        <el-tree
          ref="treeRef"
          :data="treeData"
          default-expand-all
          node-key="id"
          :props="{
            children: 'children',
            label: 'name'
          }"
          @node-click="handleNodeClick"
          @check-change="handleCheckChange"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span style="margin: 0 10px">
                <el-tooltip effect="dark" content="修改此名称" placement="top-start">
                  <el-icon color="#4ca4ff"><Edit @click.stop="edit(data.id, node)" /></el-icon>
                </el-tooltip>
                <span style="margin: 0 10px"></span>
                <el-tooltip effect="dark" content="删除此名称" placement="top-start">
                  <el-icon color="red" v-if="data.children?.length < 1"
                    ><Delete @click.stop="del(data.id, data)"
                  /></el-icon>
                </el-tooltip>
              </span>
            </span>
          </template>
        </el-tree>
      </el-card>
      <el-card class="treeTableClass">
        <el-button
          type="primary"
          :disabled="treeRow.typeName == '线别'"
          v-hasPermi="['system:shopAdministration:modelings:modeling:add']"
          @click="add"
          >新增</el-button
        >
        <!-- <el-button
          type="primary"
          :disabled="treeRow.typeName == '线别'"
          v-hasPermi="['system:shopAdministration:modelings:modeling:edit']"
          @click="edit"
          >修改</el-button
        >
        <el-button
          type="danger"
          v-hasPermi="['system:shopAdministration:modelings:modeling:remove']"
          :disabled="DelDisabled"
          @click="del(false)"
          >批量删除</el-button
        > -->
        <el-table
          class="treeTableClass"
          v-loading="loading"
          stripe
          border
          :data="TableData"
          style="margin-top: 10px"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" fixed="left" />
          <el-table-column label="序号" width="70" type="index" />
          <el-table-column label="区域类别" prop="modelingTypeDict" width="auto" />
          <el-table-column label="区域名称" prop="modelingName" width="auto" />
          <el-table-column label="区域编码" prop="modelingCode" width="auto" />
          <el-table-column label="上级编码" width="auto">
            <template #default="scope">
              {{ scope.row.superiorCode ? scope.row.superiorCode : '暂无上级编码' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" fixed="right" class-name="small-padding fixed-width">
            <template #default="scope">
              <div>
                <!-- <el-link
                  v-hasPermi="['system:shopAdministration:modelings:modeling:edit']"
                  type="primary"
                  text="修改"
                  @click="edit(scope.row.modelingId)"
                /> -->
                <el-link
                  v-hasPermi="['system:shopAdministration:modelings:modeling:remove']"
                  type="primary"
                  text="删除"
                  @click="del(scope.row.modelingId)"
                />
                <el-link
                  type="primary"
                  v-hasPermi="['system:shopAdministration:modelings:modeling:query']"
                  text="查看"
                  @click="dxamine(scope.row.modelingId)"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="query.pageNum"
      v-model:limit="query.pageSize"
      @pagination="getList"
    />
    <!-- 新增弹窗 -->
    <p-XiaoheDialog :dialogVisible="addIsShow" :title="title" @close="close" width="60%">
      <template #body>
        <div>
          <el-form
            inline
            scroll-to-error
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="140px"
            label-position="right"
            status-icon
          >
            <el-form-item label="区域类别" prop="modelingTypeDict">
              <el-input clearable disabled v-model="ruleForm.modelingTypeDict" placeholder="请填写区域类别" />
            </el-form-item>
            <el-form-item label="上级编码" prop="superiorCode" v-if="ruleForm.modelingTypeDict !== '工厂'">
              <el-input
                clearable
                :disabled="ruleForm.modelingTypeDict != '工厂' || title == '查看'"
                v-model="ruleForm.superiorCode"
                placeholder="请填写上级编码"
              />
            </el-form-item>
            <el-form-item label="区域编码" prop="modelingCode">
              <el-input
                clearable
                :disabled="title != '新增'"
                v-model="ruleForm.modelingCode"
                placeholder="请填写区域编码"
              />
            </el-form-item>
            <el-form-item label="区域名称" prop="modelingName">
              <el-input clearable :disabled="disabled" v-model="ruleForm.modelingName" placeholder="请填写区域名称" />
            </el-form-item>
            <el-form-item label="车间生产阶别" prop="modelingShopRank" v-if="ruleForm.modelingTypeDict == '车间'">
              <el-select
                v-model="ruleForm.modelingShopRank"
                clearable
                :disabled="title == '查看'"
                placeholder="请选择车间生产阶别"
              >
                <el-option
                  v-for="(item, index) in quality_production_level"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="车间下级车间" prop="modelingShopNext" v-if="ruleForm.modelingTypeDict == '车间'">
              <el-select
                v-model="ruleForm.modelingShopNext"
                clearable
                :disabled="title == '查看'"
                placeholder="请选择车间下级车间"
              >
                <el-option
                  v-for="(item, index) in cutShopModeling"
                  :key="index"
                  :label="item.modelingName"
                  :value="item.modelingCode"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item label="绑定线边仓" prop="modelingStorageType" v-if="ruleForm.modelingTypeDict == '线别'">
              <el-select
                @change="modelingStorageTypeChange"
                v-model="ruleForm.modelingStorageType"
                clearable
                :disabled="title == '查看'"
                placeholder="请选择线边仓"
              >
                <el-option v-for="(item, index) in warehouseSel" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="车间绑定仓库" prop="modelingBindingStorage">
              <el-select
                v-model="ruleForm.modelingBindingStorage"
                clearable
                :disabled="title == '查看'"
                placeholder="请选择车间绑定仓库"
              >
                <el-option v-for="(item, index) in warehouseSel" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item> -->

            <el-form-item
              label="线别最小切边(mm)"
              prop="modelingMinTrimming"
              v-if="ruleForm.modelingTypeDict == '线别' && ruleForm.modelingShopRankType == 2"
            >
              <el-input
                type="number"
                clearable
                :disabled="disabled"
                v-model="ruleForm.modelingMinTrimming"
                placeholder="请填写最小切边"
                oninput="if(value<=0)value=''"
              />
            </el-form-item>
            <!-- <el-form-item label="线别最大切边(mm)" prop="modelingMaxTrimming">
              <el-input
                type="number"
                clearable
                :disabled="disabled"
                v-model="ruleForm.modelingMaxTrimming"
                placeholder="请填写最大切边"
                oninput="if(value<=0)value=''"
              />
            </el-form-item> -->
            <el-form-item
              label="线别定幅宽(mm)"
              prop="modelingWidth"
              v-if="ruleForm.modelingTypeDict == '线别' && ruleForm.modelingShopRankType == 2"
            >
              <el-input
                type="number"
                clearable
                :disabled="disabled"
                v-model="ruleForm.modelingWidth"
                placeholder="请填写定幅宽"
                oninput="if(value<=0)value=''"
              />
            </el-form-item>
          </el-form>
          <Btn
            v-if="title != '查看'"
            :loading="Btnloading"
            @submit="title == '新增' ? addSub() : editSub()"
            @close="close"
          />
        </div>
      </template>
    </p-XiaoheDialog>
  </div>
</template>

<style lang="scss" scoped>
.treeClass {
  width: 300px;
}
</style>
